package com.nageoffer.jobtrain.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.nageoffer.jobtrain.common.toolkit.biz.user.UserInfoDTO;
import com.nageoffer.jobtrain.common.toolkit.constant.JWTPlayLoadConstant;
import com.nageoffer.jobtrain.common.toolkit.utils.JWTUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 全局网关过滤器
 * author：唐晨
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    // 全部的过滤路由请求
    private static final List<String> IGNORE_URI = Lists.newArrayList(
            "/api/job-train/admin/user/register",      // 管理员用户注册
            "/api/job-train/admin/user/login",                  // 管理员用户登录
            "/api/job-train/project/user/send-message",         // 用户登录发送验证码
            "/api/job-train/project/user/login"                 // 用户登录、注册请求
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String requestPath = request.getPath().toString();
        if (!IGNORE_URI.contains(requestPath)) {
            // 不存在白名单中，此时需要进行网关验证
            String token = request.getHeaders().getFirst("Authorization");
            UserInfoDTO userInfoDTO;
            // 验证token是否有效
            try {
                if (!StrUtil.isEmpty(token) && (userInfoDTO = JWTUtils.verifyAndGetUser(token)) != null) {
                    // 将 userInfoDTO 中的 id 和 username 设置到 header 中
                    ServerHttpRequest modifiedRequest = request.mutate()
                            .header(JWTPlayLoadConstant.LOGIN_PLAY_LOAD_ID, userInfoDTO.getId())
                            .header(JWTPlayLoadConstant.LOGIN_PLAY_LOAD_USERNAME, userInfoDTO.getUsername())
                            .build();

                    // 使用修改后的请求继续执行过滤链
                    return chain.filter(exchange.mutate()
                            .request(modifiedRequest)
                            .build());
                }
            } catch (Throwable ex) {
                // token 验证失败
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

                // 构建响应体内容
                String responseBody = JSON.toJSONString("身份信息验证失败");
                DataBuffer buffer = response.bufferFactory().wrap(responseBody.getBytes(StandardCharsets.UTF_8));

                return response.writeWith(Mono.just(buffer));
            }
        }
        // 存在白名单中，直接走下一个过滤链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
